package com.feilong.edgeAI.request;

import static com.aiibt.common.core.WDViewModel.REQUEST_TYPE_TALK_DATA;

import android.text.TextUtils;

import com.aiibt.common.bean.Result;
import com.aiibt.common.core.DataCall;
import com.aiibt.common.core.exception.ApiException;
import com.aiibt.common.core.http.NetworkManager;
import com.feilong.edgeAI.R;
import com.feilong.edgeAI.model.BaseResult;

import io.reactivex.Observable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by【仿脑科技】
 *
 * @Author: potato
 * @CreateDate: 2024/3/11 15:12
 */
public class RetrofitUtil {
    protected IMainRequest iRequest;
    public RetrofitUtil(){
        iRequest = NetworkManager.instance().create(REQUEST_TYPE_TALK_DATA, IMainRequest.class);
    }

    public void requestUrl(String key,String userid,DataCall dataCall){
        if(TextUtils.isEmpty(userid)){
            userid = "feilong";
        }
        request(iRequest.talk(key, userid, "talk_feilong"), dataCall);
    }

    /**
     * 请求数据，所有网络操作请使用本方法
     *
     * @param observable
     * @param dataCall
     * @return
     */
    public Disposable request(Observable observable, final DataCall dataCall) {
        return observable.subscribeOn(Schedulers.io())//将请求调度到子线程上
                .observeOn(AndroidSchedulers.mainThread())//观察响应结果，把响应结果调度到主线程中处理
                .onErrorReturn(new Function<Throwable, Throwable>() {//处理所有异常
                    @Override
                    public Throwable apply(Throwable throwable) throws Exception {
                        return throwable;
                    }
                })
                .subscribe(getConsumer(dataCall), new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable e) throws Exception {
                        dataCall.fail(ApiException.handleException(e));
                    }
                });
    }

    /**
     * @param
     * @return
     * @author: yintao
     * @date: 2020/4/20 11:56 PM
     * @method
     * @description 根据返回值{@link #getResponseType()}灵活改变Consumer或者自己直接重写都可以
     */
    public Consumer getConsumer(final DataCall dataCall) {
        return new Consumer<String>() {
            @Override
            public void accept(String result) throws Exception {
//                if (result.getCode() == 200) {
                    dataCall.success(result);
//                } else {
//                        dataCall.fail(new ApiException(String.valueOf(result.getErrorCode()), result.getErrorInfo()));
//                }
            }
        };
    }

}